package com.sh.rbac.core.sensitive.handler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.sh.rbac.core.security.util.SecurityHolderUtils;
import com.sh.rbac.core.sensitive.annotation.Sensitive;
import com.sh.rbac.core.sensitive.enums.SensitiveStrategy;
import com.sh.rbac.domain.entity.User;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据脱敏处理
 *
 * @author wb
 * @since 2025-11-06
 */
@Slf4j
public class SensitiveHandler extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategy strategy;
    private String[] roleKeys;
    private String[] perms;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (!isSensitive()) {
            gen.writeString(value);
            return;
        }

        // 执行脱敏
        gen.writeString(strategy.getSensitive().apply(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Sensitive annotation = property.getAnnotation(Sensitive.class);

        if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
            this.strategy = annotation.strategy();
            this.roleKeys = annotation.roleKeys();
            this.perms = annotation.perms();
            return this;
        }

        return prov.findValueSerializer(property.getType(), property);
    }

    /**
     * 判断是否需要脱敏
     *
     * @return true/false
     */
    private boolean isSensitive() {
        User loginUser = SecurityHolderUtils.getLoginUser();

        // 未登录不需要脱敏
        if (loginUser == null) {
            return false;
        }

        // 管理员不需要脱敏
        if (SecurityHolderUtils.isAdmin()) {
            return false;
        }

        // 检查角色权限
        if (roleKeys != null) {
            for (String roleKey : roleKeys) {
                if (loginUser.getRoles().stream().anyMatch(role -> role.getRoleKey().equals(roleKey))) {
                    return false;
                }
            }
        }

        // 检查具体权限
        if (perms != null) {
            for (String perm : perms) {
                if (loginUser.getPermissions().contains(perm)) {
                    return false;
                }
            }
        }

        // 默认需要脱敏
        return true;
    }
}
